package com.glodon.zhuanli.system.service;

import com.glodon.zhuanli.common.MapConverter;
import com.glodon.zhuanli.common.Maps2;
import com.glodon.zhuanli.common.service.ZhuanliBaseServiceImpl;
import com.glodon.zhuanli.system.dao.SysRoleDao;
import com.glodon.zhuanli.system.entity.SysRole;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class SysRoleService extends ZhuanliBaseServiceImpl<SysRole , SysRoleDao> {
	
	/**
	 * 查询条件表达式
	 */
	private LinkedHashMap<String, String> expressionMap = new LinkedHashMap<String , String>(){
			{
				put("name" , "name:LIKE") ;
				put("companyId" , "companyId:EQ") ;
				put("system" , "companyId:ISNULL") ;
				put("ids" , "id:IN") ;
	       }
	};
	
	@Override
	public LinkedHashMap<String, String> getQueryExpressions() {
		return expressionMap ;
	}

	@Transactional
	@Override
	public void delete(String id) {
		if( isBlankId(id) ){
			return ;
		}

		//判断角色类型
		SysRole sysRole = get( id ) ;
		if( sysRole!=null && StringUtils.equalsIgnoreCase(sysRole.getType() , "system")){
			log.info("系统内置角色不能删除");
			return ;
		}
		super.delete(id);
	}

	/**
	 * 判断是会否为管理员
	 * @param roleId
	 * @return
	 */
	public boolean isAdmin(String roleId){
		if( StringUtils.isBlank(roleId) ){
			return false ;
		}
		SysRole sysRole = get( roleId ) ;
		if( sysRole!=null && StringUtils.equalsIgnoreCase(sysRole.getCode() , "admin")){
			return true ;
		}
		return false ;
	}

	public Map<String,String> getRoleNameMap(Set<String> roleIds){
		if(CollectionUtils.isEmpty(roleIds)){
			return null ;
		}

		Map<String,Object> searchParams = Maps.newHashMap() ;
		searchParams.put("ids" , roleIds) ;

		List<Map<String, Object>> resultList = this.entityDao.queryMultiFields( new String[]{"name" , "id"} ,
				getQuerySpecification( searchParams ) ) ;

		return Maps2.toMap(resultList, new MapConverter<Map<String,Object>, String,String>() {
			@Override
			public String getKey(Map<String, Object> item) {
				return item.get("id").toString() ;
			}

			@Override
			public String getValue(Map<String, Object> item) {
				return item.get("name")!=null ? item.get("name").toString() : "" ;
			}
		}) ;
	}
	

}
